<?php
class WikiController extends ManagerController {
	function WikiController(){
		parent::ManagerController();
	}

	function index(){
		$mod = new DictModel();
		$this->init_page_info(15);
		$condition = array('site_id'=>SITE_ID);
		$total = $mod->count($condition);
		$this->set_page_total($total);
		if($total>0){
			$dicts = $mod->find($condition, null, $this->page_info->get_start(), $this->page_info->page_size, array('update_time'=>-1));
			$this->assign('dicts', $dicts);
		}
		$this->page_title = 'WIKI管理 - ' . $this->site_info['name'];
		$this->assign('types', $this->get_wiki_types());
		$this->display();
	}
	
	public function clean_cache($word=null){
		if($word === null){
			$word = $_POST['word'];
		}
		DictModel::clean_cache(MAIN_DOMAIN, $word);
		$this->ajax_info('词条："' . $_POST['word'] . '"缓存已经清理！');
	}
	
	public function del_wiki(){
		$mod = new DictModel();
		$image_mod = new ImageModel();
		$dict = $mod->get_by_key_site_limit($this->id);
		if(empty($dict)){
			$this->ajax_error('您要删除的词条不存在或已被删除！');
		}
		if(isset($dict['items'])){
			foreach($dict['items'] as $index=>$item){
				if(isset($item['images'])){
					foreach($item['images'] as $image_id => $image){
						//删除图片
						$path = $image['file'];
						self::_del_image($path);
						
						//删除image数据表内的记录
						$image_mod->delete_by_key($image_id);
					}
				}
			}
		}
		//删除图片目录
		$dict_image_path = ROOT_PATH . '/sites/main/' . MAIN_DOMAIN . '/file/' . date('Y_m', $dict['create_time']) . '/' . $this->id;
		if(is_dir($dict_image_path)){
			yu_mkdirs($dict_image_path);
		}
		$mod->delete_by_key_site_limit($this->id);
		DictModel::clean_cache(MAIN_DOMAIN, $dict['word']);
		$this->ajax_info("删除成功！");
	}
	
	private function _del_image($path){
		$path = ROOT_PATH . $path;
		//删除原图
		if(is_file($path)){
			unlink($path);
		}
		$thumbs = array('80x80', '50x50', '150x150', '680x680');
		foreach($thumbs as $thumb){
			$thumb_path = preg_replace('%^(.*)/([^/]*)$%', '$1/' . $thumb . '/$2', $path);
			if(is_file($thumb_path)){
				unlink($thumb_path);
			}
		}
	}
	
	public function exchange(){
		$mod = new DictModel();
		$this->init_page_info(200);
		$total = $mod->count();
		$this->set_page_total($total);
		$dicts = $mod->find(null, null, $this->page_info->get_start(), $this->page_info->page_size);
		foreach ($dicts as $id=>$dict){
			if(isset($dict['history'])){
				echo '删除历史记录<br>';
				$mod->delete_column_by_key($id, 'history');
			}
			foreach ($dict['items'] as $index=>$item){
				if($item['available'] === false){
					echo '删除目录：' . $index . '<br>';
					$mod->delete_column_by_key($id, 'items.' . $index);
					continue;
				}
				if(isset($item['images'])){
					$images = $item['images'];
					echo '删除图片<br>';
					$mod->delete_column_by_key($id, 'items.' . $index . '.images');
					$new_images = array();
					foreach($images as $image){
						if(isset($image['image_id'])){
							$image_id = $image['image_id'];
							unset($image['image_id']);
							$new_images[$image_id] = $image;
						}
					}
					if(count($new_images)>0){
						echo '重新生成图片<br>';
						$mod->update_by_key($id, array('items.' . $index . '.images'=>$new_images));
					}
				}
			}
		}
	}
	
	/**
	 * 编辑框架，本方法不对内容进行修改，但可以对框架进行编辑
	 */
	public function edit(){
		$mod = new DictModel();
		$dict = $mod->get_by_key_site_limit($this->id);
		$dict['items'] = SortHelper::sortByCol($dict['items'], 'rank', SORT_ASC);
		$this->assign('dict', $dict);
		$this->page_title = "WIKI框架编辑 - {$dict['word']} - {$this->site_info['name']}";
		$this->display();
	}
	
	public function set_word(){
		$mod = new DictModel();
		$word = self::format($_POST['word']);
		if(empty($word)){
			$this->ajax_error('词条不能为空！');
		}
		$dict = $mod->get_by_key_site_limit($this->id, 'word');
		if(empty($dict)){
			$this->ajax_error('词条：' . $word . ' 不存在！');
		}
		if($dict['word'] == $word){
			$this->ajax_error('没有修改！');
		}
		if($mod->exists_attrs(array('site_id'=>SITE_ID, 'word'=>$word))){
			$this->ajax_error('词条：' . $word . '已经存在！');
		}
		//修改
		$mod->update_by_key_site_limit($this->id, array('word'=>$word));
		
		//清除缓存
		DictModel::clean_cache(MAIN_DOMAIN, $word);
		$this->ajax_info('修改成功！');
	}
	
	public function set_index(){
		$mod = new DictModel();
		$index = trim($_POST['index']);
		$new_index = trim($_POST['new_index']);
		if($index == $new_index){
			$this->assign('没有修改！');
		}
		$dict = $mod->get_by_key_site_limit($this->id, 'word,items.' . $index . ',items.' . $new_index . ',history.' . $index);
		if(empty($dict)){
			$this->assign('词条不存在！');
		}
		if(!isset($dict['items'][$index])){
			$this->assign('词条目录：' . $index . ' 不存在！');
		}
		if(!isset($dict['items'][$new_index])){
			$this->assign('词条目录：' . $new_index . ' 已经存在！');
		}
		//修改
		$update_data = array('items.' . $new_index=>$dict['items'][$index]);
		if(isset($dict['history'][$index])){
			$update_data['history . ' . $new_index] = $dict['history'][$index];
		}
		$mod->update_by_key_site_limit($this->id, $update_data);
		//删除旧的
		$mod->delete_column_by_key($this->id, 'items.'.$index . ',history.'.$index);

		//清除缓存
		DictModel::clean_cache(MAIN_DOMAIN, $dict['word']);
		$this->ajax_info('更新成功！');
	}

	/**
	 * 格式化词条，将.换成全角的点号
	 * @param unknown_type $word
	 */
	private function format(&$word){
		$word = preg_replace('/\./', '．', $word);
		$word = trim($word);
		return $word;
	}
	
	/**
	 * 引用为..
	 */
	function used(){
		if(IS_POST){
			$wiki_ids = $_POST['wiki'];
			$word_type = $_POST['word_type'];
			$mod = new RecommendModel();
			$wr = $mod->get_by_attrs(array('model'=>'wiki', 'type'=>$word_type, 'site_id'=>SITE_ID));
			$is_new = false;
			if(empty($wr)){
				$is_new = true;
				$wr = array(
					'_id' => gen_guid(),
					'model' => 'wiki',
					'type' => $word_type,
					'site_id' => SITE_ID,
				);
			}
			$dict_mod = new DictModel();
			$wikis = $dict_mod->find(array('_id'=>array('$in'=>$wiki_ids)), 'word,author,add_time');
			$i = 100;
			foreach ($wiki_ids as $wiki_id){
				if(isset($wr['items'][$wiki_id]))
					continue;
				$dict = $wikis[$wiki_id];
				$wr['items'][$wiki_id] = array(
					'id' => $wiki_id,
					'word' => $dict['word'],
					'title' => $dict['word'],
					'author' => $dict['author'],
					'add_time' => $dict['add_time'],
					'rank' => $i,
				);
				++$i;
			}
			if($is_new){
				$mod->insert($wr);
			}else{
				$mod->update_by_key($wr['_id'], $wr);
			}
			//保存成功，跳转到处理页面
			$this->redirect('/manager.php?app=wiki&act=recommend&type=' . $word_type);
		}
	}
	
	public function recommend(){
		$mod = new RecommendModel();
		if(isset($_REQUEST['type'])){
			$type = $_REQUEST['type'];
		}else{
			$type = 0;
		}
		$recommend = $mod->get_by_attrs(array('type'=>$type, 'model'=>'wiki', 'site_id'=>SITE_ID));
		if(!empty($recommend)){
			$recommend['items'] = SortHelper::sortByCol($recommend['items'], 'rank');
			$this->assign('recommend', $recommend);
		}
		$this->assign('types', $this->get_wiki_types());
		$this->display();
	}
	
	public function sort(){
		$mod = new RecommendModel();
		$type = $_POST['type'];
		$ids = $_POST['ids'];
		$recommend = $mod->get_by_attrs(array('type'=>$type, 'model'=>'wiki', 'site_id'=>SITE_ID));
		$id_list = explode(';', $ids);
		$i = 0;
		foreach ($id_list as $id){
			if(empty($id))continue;
			$recommend['items'][$id]['rank'] = $i;
			++$i;
		}
		$mod->update_by_attrs(array('type'=>$type, 'model'=>'wiki', 'site_id'=>SITE_ID), $recommend);
		$this->ajax_info('保存成功！');
	}
	
	public function add_recommend(){
		$type = $_POST['type'];
		$word = $_POST['word'];
		$dict_mod = new DictModel();
		$dict = $dict_mod->get_by_attrs(array('word'=>$word, 'site_id'=>SITE_ID), 'word,author,add_time');
		if(empty($dict)){
			$this->ajax_error('词条不存在：' . $word);
		}
		$wr = array(
			'id' => $dict['_id'],
			'word' => $dict['word'],
			'title' => $dict['word'],
			'author' => $dict['author'],
			'add_time' => $dict['add_time'],
			'rank' => 1000,
		);
		$mod = new RecommendModel();
		$mod->update_by_attrs(array('type'=>$type, 'model'=>'wiki', 'site_id'=>SITE_ID), array('items.' . $dict['_id']=>$wr));
		$this->ajax_info('追加成功！');
	}
	
	public function del_recommend(){
		$wiki_ids = $_POST['ids'];
		$type = $_POST['type'];
		$mod = new RecommendModel();
		foreach($wiki_ids as $id){
			if(empty($id))continue;
			$mod->delete_column(array('type'=>$type, 'model'=>'wiki', 'site_id'=>SITE_ID), 'items.' . $id);
		}
		$this->ajax_info('删除成功！');
	}
	
	public function edit_recommend(){
		$mod = new RecommendModel();
		if(IS_POST){
			$rid = self::get_post_val('rid');
			$title = self::get_post_val('title');
			$desc = self::get_post_val('desc');
			$width = self::get_post_int_val('width');
			$height = self::get_post_int_val('height');
			$image = self::get_post_val('image');
			//
			if(starts_with($image, CACHE_URL)){
				$image = substr($image, strlen(CACHE_URL));
			}
			$image = preg_replace('%/\d+x\d+/%', '/', $image);
			$recommend = $mod->get_by_key_site_limit($rid, 'type,items.' . $this->id);
			$mod->update_by_key_site_limit($rid, array(
				'width' => $width,
				'height' => $height,
				'items.' . $this->id . '.title' => $title,
				'items.' . $this->id . '.desc' => $desc,
				'items.' . $this->id . '.image' => $image,
				'items.' . $this->id . '.src_image' => $image,
			));
			$this->redirect('/manager.php?app=wiki&act=recommend&type=' . $recommend['type']);
		}
		$dict_mod = new DictModel();
		$dict = $dict_mod->get_by_key_site_limit($this->id, 'word,items');
		$this->assign('dict', $dict);
		$recommend = $mod->get_by_key_site_limit($_GET['rid'], 'height,width,items.' . $this->id);
		$this->assign('recommend', $recommend['items'][$this->id]);
		$this->assign('height', $recommend['height']);
		$this->assign('width', $recommend['width']);
		$this->display();
	}
	
	public function edit_recommend_image(){
		$mod = new RecommendModel();
		$rid = $_REQUEST['rid'];
		$recommend = $mod->get_by_key_site_limit($rid, 'type,title,desc,height,width,items.' . $this->id);
		if(IS_POST){
			$x = self::get_post_int_val('x');
			$y = self::get_post_int_val('y');
			$x2 = self::get_post_int_val('x2');
			$y2 = self::get_post_int_val('y2');
			$w = self::get_post_int_val('w');
			$h = self::get_post_int_val('h');
// 			$this->ajax_error($x . 'x' . $y);
			$ih = new ImageHandler();
			$src = ROOT_PATH . get_thumb_path($recommend['items'][$this->id]['src_image'], '680x680');
			$file_ext = get_file_ext($src);
			$ih->setSrcImg($src);
			$dst = '/sites/main/' . MAIN_DOMAIN . '/file/' . date('Y_m') . '/' . gen_guid() . $file_ext;
			$ih->setDstImg(ROOT_PATH . $dst);
			$ih->setSrcCutPosition($x,$y);
			$ih->setRectangleCut($w,$h);
			$ih->setCutType(2);
			$ih->createImg(intval($recommend['width']), intval($recommend['height']));
			$ih2 = new ImageHandler();
			$ih2->setSrcImg(ROOT_PATH . $dst);
			$ih->setCutType(1);
			$ih2->setDstImg(ROOT_PATH . $dst);
			$ih2->createImg(intval($recommend['width']), intval($recommend['height']));
			$mod->update_by_key_site_limit($rid, array(
				'items.' . $this->id . '.image' => $dst
			));
			//删除旧图片
			if(is_file(ROOT_PATH . $recommend['items'][$this->id]['image'])){
				unlink(ROOT_PATH . $recommend['items'][$this->id]['image']);
			}
			$this->ajax_info('保存成功！');
		}
		$this->assign(array(
			'recommend' => $recommend['items'][$this->id],
			'width' => $recommend['width'],
			'height' => $recommend['height'],
			'type' => $recommend['type']
		));
		$this->display();
	}
	
	public function image_list(){
		$mod = new DictModel();
		$dict = $mod->get_by_key_site_limit($this->id);
		$dict['items'] = SortHelper::sortByCol($dict['items'], 'rank', SORT_ASC);
		$this->assign('dict', $dict);
		$this->page_title = "WIKI图片编辑 - {$dict['word']} - {$this->site_info['name']}";
		$this->display();
	}
	
	public function del_img(){
		$index = $_GET['index'];
		$img_index = $_GET['img_index'];
		$mod = new DictModel();
		$dict = $mod->get_by_key_site_limit($this->id, 'word,items.' . $index . '.images.' . $img_index);
		if(empty($dict)){
			$this->ajax_error('您要删除的图片不存在或已被删除！');
		}
		$image_id = $dict['items'][$index]['images'][$img_index]['image_id'];
		$mod->delete_column_by_key($this->id, 'items.' . $index . '.images.' . $img_index);
		//删除Image内数据
		if(!empty($image_id)){
			$image_mod = new ImageModel();
			$image_mod->delete_column_by_key($image_id);
		}
		//清除缓存
		$this->clean_cache($dict['word']);
		$this->ajax_info('删除成功！');
	}
	
	private function get_wiki_types(){
		return array(
			'热门词条',
			'新词条推荐'
		);
	}
}

?>